// src/main/ipc-handlers.js - 修正版本
const AuthService = require('./auth-service');
const ExportConfigService = require('./exportConfig');

// 创建全局服务实例
let authService = null;
let exportConfigService = null;

function setupAuthHandlers(ipcMain, mainWindow) {
  let currentSession = null;

  // 设置认证服务实例
  ipcMain.handle('set-auth-service', async (event, serviceInstance) => {
    authService = serviceInstance;
    return { success: true };
  });

  // 设置导出配置服务实例
  ipcMain.handle('set-export-config-service', async (event, serviceInstance) => {
    exportConfigService = serviceInstance;
    return { success: true };
  });

  // 新增导出配置查询
ipcMain.handle('export-config-get', async (event, queryParams) => {
  try {
    if (!exportConfigService) {
      exportConfigService = new ExportConfigService();
    }
    const result = await exportConfigService.getExportConfigs(queryParams);
    
    // 确保返回的数据是可序列化的
    const safeData = {
      list: result.list.map(item => ({
        id: item.id,
        groupName: item.groupName,
        viewableUnits: item.viewableUnits, // 已经是字符串数组，是可序列化的
        viewableTables: item.viewableTables.map(table => ({
          name: table.name
        }))
      })),
      total: result.total
    };
    return { 
      success: true,
      data: safeData
    };
  } catch (error) {
    console.error('获取导出配置失败:', error);
    return { 
      success: false, 
      error: error.message 
    };
  }
});

  // 初始化认证系统
  ipcMain.handle('auth-initialize', async () => {
    try {
      if (!authService) {
        authService = new AuthService();
      }
      return await authService.initialize();
    } catch (error) {
      console.error('认证初始化失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 首次设置
  ipcMain.handle('auth-first-time-setup', async (event, { username, password }) => {
    try {
      if (!authService) {
        throw new Error('认证服务未初始化');
      }
      
      const result = await authService.handleFirstTimeSetup(username, password);
      
      if (result.success) {
        // 首次设置成功后自动登录
        const loginResult = await authService.handleLogin(username, password);
        if (loginResult.success) {
          currentSession = loginResult.sessionToken;
        }
        return loginResult;
      }
      
      return result;
    } catch (error) {
      console.error('首次设置失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 用户登录
  ipcMain.handle('auth-login', async (event, { username, password }) => {
    try {
      if (!authService) {
        throw new Error('认证服务未初始化');
      }
      
      const result = await authService.handleLogin(username, password);
      if (result.success) {
        currentSession = result.sessionToken;
      }
      return result;
    } catch (error) {
      console.error('登录失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 验证会话
  ipcMain.handle('auth-verify-session', async (event, sessionToken) => {
    try {
      if (!authService) {
        throw new Error('认证服务未初始化');
      }
      
      if (!sessionToken && currentSession) {
        sessionToken = currentSession;
      }
      
      if (sessionToken && authService.checkSessionTimeout(sessionToken)) {
        // 会话超时，需要重新登录
        await authService.handleLogout(sessionToken);
        currentSession = null;
        return { success: false, error: '会话已超时，请重新登录', timeout: true };
      }

      const result = await authService.verifySession(sessionToken);
      if (!result.success) {
        currentSession = null;
      }
      return result;
    } catch (error) {
      console.error('会话验证失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 用户登出
  ipcMain.handle('auth-logout', async (event, sessionToken) => {
    try {
      if (!authService) {
        throw new Error('认证服务未初始化');
      }
      
      const result = await authService.handleLogout(sessionToken || currentSession);
      currentSession = null;
      return result;
    } catch (error) {
      console.error('登出失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 获取当前会话信息
  ipcMain.handle('auth-get-session', async () => {
    try {
      if (!authService || !currentSession) {
        return { success: false, error: '无活跃会话' };
      }

      const result = await authService.verifySession(currentSession);
      return result;
    } catch (error) {
      console.error('获取会话失败:', error);
      return { success: false, error: error.message };
    }
  });

  // 定期清理过期会话
  setInterval(() => {
    if (authService) {
      authService.cleanupExpiredSessions();
    }
  }, 60 * 1000);
}

module.exports = { setupAuthHandlers };